# Appendix Q
# Santiago Lopez-Cariboni, 2022. "Political Regimes and Informal Social Insurance", Comparative Political Studies.


# ---- wd ----
wd <- 'replication_materials' 
setwd(wd)

# ---- packages ----
pkgs <- c("data.table", "foreign", 'panelView', 'fect', "lubridate", 
    "ggplot2", "dplyr", "mFilter", "texreg", "AER", "xts", "interflex", "gridExtra")
suppressPackageStartupMessages(sapply(pkgs,require,character.only=T))
# Plot the effects (use Johannes Karreth's function: https://github.com/jkarreth/JKmisc/blob/master/ggintfun.R)
# devtools::source_url("https://raw.githubusercontent.com/jkarreth/JKmisc/master/ggintfun.R")
source('code/functions/ggintfun.R')
# Function for time Lags
source('code/functions/lagpanel.R')


# ---- data ----
dt <- fread('data/dt_replication.csv')
dt <- dt[LDC==1, ]

# ---- Figure Q1 ----
m1 <- lm(outgap.tdl ~ l.outgap.tdl 
    + l.outgap.gdp.hamilton
    + l.democracy
    + as.factor(iso3c)
    + as.factor(year)
     ,
    data=dt, na.action=na.omit)
# summary(m1,  diagnostics = TRUE)
iso3c.m <- as.character(unique(m1$model[['as.factor(iso3c)']]))

pd <- dt[iso3c %in% iso3c.m & LDC==1 & year>=1970 & year<=2014,]
length(unique(pd$iso3c))

pdf("figures/OA/Q1_treatment_map.pdf", width = 5, height = 5)
panelView(tdlosses ~ democracy + tdlosses, data = as.data.frame(pd), 
    index = c("iso3c","year"), 
    by.timing = TRUE,
  axis.lab = "time", xlab = "Time", ylab = "Country",
  background = "white", main = "", legend.labs=c("N/A", "Autocracy", "Democracy"),
cex.axis = 3, theme.bw = FALSE)
dev.off()

# ---- Figure Q2 ----
pdf("figures/OA/Q2_tdlosses_treatment.pdf", width = 5, height = 5)
panelView(tdlosses ~ democracy, data = dt[LDC==1,], 
    index = c("iso3c","year"), 
    type = "outcome", main = "",theme.bw = TRUE)
dev.off()



